/*
 * Copyright (C) 2008 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.cloudwalk.libscan.decoding;

import android.os.Handler;
import android.os.Looper;

import com.cloudwalk.libscan.manager.CloudScanManager;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;

import java.util.Hashtable;
import java.util.Vector;
import java.util.concurrent.CountDownLatch;

/**
 * This thread does all the heavy lifting of decoding the images.
 * �����߳�
 */
public final class DecodeThread extends Thread {

    private final Hashtable<DecodeHintType, Object> hints;
    private Handler handler;
    private final CountDownLatch handlerInitLatch;

    public DecodeThread() {
        handlerInitLatch = new CountDownLatch(1);
        hints = new Hashtable<>(3);
        Vector<BarcodeFormat> decodeFormats = new Vector<>();
        if (decodeFormats == null || decodeFormats.isEmpty()) {
            decodeFormats = new Vector<BarcodeFormat>();
            decodeFormats.addAll(CloudScanManager.ONE_D_FORMATS);
            decodeFormats.addAll(CloudScanManager.QR_CODE_FORMATS);
            decodeFormats.addAll(CloudScanManager.DATA_MATRIX_FORMATS);
        }
        hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
//        hints = new Hashtable<>();
//        hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
//        hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
//        hints.put(DecodeHintType.POSSIBLE_FORMATS, BarcodeFormat.QR_CODE);

    }

    public Handler getHandler() {
        try {
            handlerInitLatch.await();
        } catch (InterruptedException ie) {
            // continue?
        }
        return handler;
    }

    @Override
    public void run() {
        //开启一个消息循环
        Looper.prepare();
        handler = new DecodeHandler(hints);
        handlerInitLatch.countDown();
        //写在Looper.loop()之后的代码不会被执行，这个函数内部是一个循环，当调用Looper.myLooper().quit();后，loop才会中止，其后的代码才能得以运行
        Looper.loop();
    }

}
